﻿using JWT.MvcDemo.Help;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace JWT.MvcDemo.App_Start
{
    public class MyAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
    {

        private readonly string TimeStamp = ConfigurationManager.AppSettings["TimeStamp"];
        private readonly string LoginKey = ConfigurationManager.AppSettings["LoginKey"];
        public MyAuthorizeAttribute(bool _isCheck = true)
        {
            this.isCheck = _isCheck;
        }
        private bool isCheck { get; }

        /// <summary>
        /// 验证核心代码
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var httpContext = filterContext.HttpContext;
            var actionDescription = filterContext.ActionDescriptor;
            if (actionDescription.IsDefined(typeof(AllowAnonymousAttribute), false) ||
               actionDescription.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), false)) { return; }
            if (!isCheck) return;
            var cookie = filterContext.HttpContext.Request.Cookies.Get(LoginKey);
            //没有token 或者token过期
            if (cookie == null)
            {
                HandleUnauthorizedRequest(filterContext);
                return;
            }
            //判断是请求方法
            if (httpContext.Request.IsAjaxRequest())
            {
                //前端请求api时会将token存放在名为"auth"的请求头中
                var authHeader = httpContext.Request.Headers["auth"];
                if (authHeader == null)
                {
                    HandleUnauthorizedRequest(filterContext);
                    return;
                }
                    

                //请求参数
                //string requestTime = httpContext.Request["rtime"]; //请求时间经过DESC签名
                //if (string.IsNullOrEmpty(requestTime))
                //{
                //    HandleUnauthorizedRequest(filterContext);
                //    return;
                //}


                //请求时间RSA解密后加上时间戳的时间即该请求的有效时间
                DateTime Newdt = DateTime.Now; //服务器接收请求的当前时间
                DateTime Requestdt = DateTime.Now.AddMinutes(int.Parse(TimeStamp));

                if (Requestdt < Newdt)
                {
                    HandleUnauthorizedRequest(filterContext);
                    return;
                }
                else
                {
                    //进行其他操作
                    var userinfo = JwtHelp.GetJwtDecode(authHeader);
                    //举个例子  生成jwtToken 存入redis中    
                    //这个地方用jwtToken当作key 获取实体val   然后看看jwtToken根据redis是否一样
                    if (userinfo.UserName == "admin" && userinfo.Pwd == "123")
                    {
                        HandleUnauthorizedRequest(filterContext);
                        return;
                    }
                }
            }
           
            //HandleUnauthorizedRequest(filterContext);
        }
        /// <summary>
        /// 验证失败处理
        /// </summary>
        /// <param name="filterContext"></param>
        protected  void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            var httpContext = filterContext.HttpContext;
            if (httpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult()
                {
                    Data = new { Status = "Fail", Message = "403 Forbin", StatusCode = "403" },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                filterContext.Result = new RedirectResult(("/Login/Index"));
            }
            // base.HandleUnauthorizedRequest(filterContext);
            //filterContext.Result = new RedirectResult("/Error");
            //filterContext.HttpContext.Response.Redirect("/Home/Error");
        }

        
    }
}